package com.cjie.ecommerce.dao;

import java.math.BigDecimal;
import java.util.List;

import com.cjie.ecommerce.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 商品数据访问层（模拟数据库）
 */
@Repository
@Slf4j
public class ProductWithSimpleCacheRepository {

    // 模拟数据库存储
    private final ConcurrentHashMap<Long, Product> productDB = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1000);

    public ProductWithSimpleCacheRepository() {
        // 初始化测试数据
        initTestData();
    }

    private void initTestData() {
        save(new Product(10001L, "iPhone 15", "a0001", new BigDecimal("6999.00"),
                "苹果最新旗舰手机", 1000, "http://example.com/iphone15.jpg", true));
        save(new Product(10002L, "小米13 Pro", "a0001", new BigDecimal("4999.00"),
                "小米旗舰手机", 2000, "http://example.com/mi13pro.jpg", true));
        save(new Product(10003L, "华为MateBook X Pro", "a0002", new BigDecimal("8999.00"),
                "华为旗舰笔记本", 500, "http://example.com/matebookxpro.jpg", false));
        save(new Product(10004L, "戴尔XPS 15", "a0002", new BigDecimal("12999.00"),
                "戴尔旗舰笔记本", 300, "http://example.com/xps15.jpg", false));
    }

    public Product save(Product product) {
        if (product.getId() == null) {
            product.setId(idGenerator.incrementAndGet());
        }
        productDB.put(product.getId(), product);
        return product;
    }

    public Product findById(Long id) {
        //模拟数据库查询延迟
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            log.error("ProductWithSimpleCacheRepository.findById,sleep error,id:{}", id, e);
        }

        //模拟数据库查询
        return productDB.get(id);
    }

    /**
     * 获取指定分类下的精选产品
     *
     * @param categoryId 类别的编号
     * @return
     */
    public List<Product> getSelectedProductsByCategoryId(String categoryId) {
        //这个分类下的精选产品（实际项目中是查数据库并通过一些繁琐的业务逻辑处理得到的）
        List<Product> selectedProducts = productDB.values().stream()
                .filter(product -> product.getCategoryId().equals(categoryId))
                .collect(Collectors.toList());
        log.debug("getSelectedProductsByCategoryId,selectedProducts:{}", selectedProducts);
        return selectedProducts;
    }

    public List<Product> findAll() {
        //模拟数据库查询延迟
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            log.error("ProductWithSimpleCacheRepository.findAll,sleep error", e);
        }

        return new ArrayList<>(productDB.values());
    }

    public List<Product> findByHot(boolean hot) {
        //模拟数据库查询延迟
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            log.error("ProductWithSimpleCacheRepository.findAll,sleep error", e);
        }

        List<Product> result = new ArrayList<>();
        productDB.values().forEach(product -> {
            if (product.getHot() == hot) {
                result.add(product);
            }
        });
        return result;
    }

    public void deleteById(Long id) {
        productDB.remove(id);
    }
}
